import BasePlugin from './BasePlugin';
import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;

/**
 * 网格插件 - 处理画布网格和对齐功能
 */
export default class GridPlugin extends BasePlugin {
    constructor() {
        super();
        this.gridSize = 20;
        this.gridColor = 'rgba(0,0,0,0.1)';
        this.snapThreshold = 5;
        this.showGrid = false;
        this.snapToGrid = false;
        this.gridLines = [];
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._createGrid();
        this._setupSnapEvents();
    }

    /**
     * 显示网格
     */
    show() {
        if (!this.isEnabled() || !this.canvas) return;

        this.showGrid = true;
        this._drawGrid();
        this.canvas.renderAll();
    }

    /**
     * 隐藏网格
     */
    hide() {
        if (!this.isEnabled() || !this.canvas) return;

        this.showGrid = false;
        this._clearGrid();
        this.canvas.renderAll();
    }

    /**
     * 切换网格显示状态
     */
    toggle() {
        if (this.showGrid) {
            this.hide();
        } else {
            this.show();
        }
    }

    /**
     * 启用网格对齐
     */
    enableSnapping() {
        if (!this.isEnabled() || !this.canvas) return;
        this.snapToGrid = true;
    }

    /**
     * 禁用网格对齐
     */
    disableSnapping() {
        if (!this.isEnabled() || !this.canvas) return;
        this.snapToGrid = false;
    }

    /**
     * 设置网格大小
     */
    setGridSize(size) {
        if (!this.isEnabled() || !this.canvas) return;

        this.gridSize = size;
        if (this.showGrid) {
            this._clearGrid();
            this._drawGrid();
            this.canvas.renderAll();
        }
    }

    /**
     * 设置网格颜色
     */
    setGridColor(color) {
        if (!this.isEnabled() || !this.canvas) return;

        this.gridColor = color;
        if (this.showGrid) {
            this._clearGrid();
            this._drawGrid();
            this.canvas.renderAll();
        }
    }

    /**
     * 设置对齐阈值
     */
    setSnapThreshold(threshold) {
        if (!this.isEnabled()) return;
        this.snapThreshold = threshold;
    }

    /**
     * 创建网格
     */
    _createGrid() {
        if (!this.canvas) return;

        const width = this.canvas.width;
        const height = this.canvas.height;

        // 创建垂直线
        for (let i = 0; i <= width; i += this.gridSize) {
            const line = new fabric.Line([i, 0, i, height], {
                stroke: this.gridColor,
                selectable: false,
                evented: false,
                excludeFromExport: true
            });
            this.gridLines.push(line);
        }

        // 创建水平线
        for (let i = 0; i <= height; i += this.gridSize) {
            const line = new fabric.Line([0, i, width, i], {
                stroke: this.gridColor,
                selectable: false,
                evented: false,
                excludeFromExport: true
            });
            this.gridLines.push(line);
        }
    }

    /**
     * 绘制网格
     */
    _drawGrid() {
        if (!this.canvas) return;

        this.gridLines.forEach(line => {
            this.canvas.add(line);
            line.sendToBack();
        });
    }

    /**
     * 清除网格
     */
    _clearGrid() {
        if (!this.canvas) return;

        this.gridLines.forEach(line => {
            this.canvas.remove(line);
        });
    }

    /**
     * 设置对齐事件
     */
    _setupSnapEvents() {
        if (!this.canvas) return;

        this.canvas.on('object:moving', (e) => {
            if (!this.snapToGrid) return;

            const obj = e.target;
            const gridSize = this.gridSize;
            const threshold = this.snapThreshold;

            // 计算对象中心点
            const center = obj.getCenterPoint();

            // 计算最近的网格线
            const snapX = Math.round(center.x / gridSize) * gridSize;
            const snapY = Math.round(center.y / gridSize) * gridSize;

            // 如果对象中心点接近网格线，则对齐
            if (Math.abs(center.x - snapX) < threshold) {
                obj.set({
                    left: snapX - obj.width * obj.scaleX / 2
                });
            }
            if (Math.abs(center.y - snapY) < threshold) {
                obj.set({
                    top: snapY - obj.height * obj.scaleY / 2
                });
            }
        });

        this.canvas.on('object:scaling', (e) => {
            if (!this.snapToGrid) return;

            const obj = e.target;
            const gridSize = this.gridSize;
            const threshold = this.snapThreshold;

            // 计算对象的实际尺寸
            const width = obj.width * obj.scaleX;
            const height = obj.height * obj.scaleY;

            // 计算最接近的网格尺寸
            const snapWidth = Math.round(width / gridSize) * gridSize;
            const snapHeight = Math.round(height / gridSize) * gridSize;

            // 如果尺寸接近网格尺寸，则对齐
            if (Math.abs(width - snapWidth) < threshold) {
                obj.set({
                    scaleX: snapWidth / obj.width
                });
            }
            if (Math.abs(height - snapHeight) < threshold) {
                obj.set({
                    scaleY: snapHeight / obj.height
                });
            }
        });

        this.canvas.on('object:rotating', (e) => {
            if (!this.snapToGrid) return;

            const obj = e.target;
            const threshold = this.snapThreshold;

            // 计算最接近的45度角
            const angle = obj.angle;
            const snapAngle = Math.round(angle / 45) * 45;

            // 如果角度接近45度的倍数，则对齐
            if (Math.abs(angle - snapAngle) < threshold) {
                obj.set({
                    angle: snapAngle
                });
            }
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this._clearGrid();
            this.gridLines = [];
        }
        super.destroy();
    }
} 